/*
** main.c for  in /home/guicqu_g//svn/rush-epikong/etape_2/maps/gen
** 
** Made by gallien guicquero
** Login   <guicqu_g@epitech.net>
** 
** Started on  Sat Mar 26 14:09:16 2011 gallien guicquero
** Last update Sat Mar 26 15:05:15 2011 gallien guicquero
*/

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/*
**	Legende
*/

#define		CHAR_WALL	'w'
#define		CHAR_LADDER	's'
#define		CHAR_MONSTER	'm'
#define		CHAR_OUTPUT	'o'
#define		CHAR_INPUT	'i'
#define		CHAR_KEY	'k'
#define		CHAR_LEVEL	'.'

int	gen_ladder(char **map, int x, int y, int xoff, int yoff)
{
  map[yoff][xoff] = CHAR_LADDER;
  while (yoff < y - 1 && xoff < x - 1 && map[yoff][xoff] != CHAR_WALL)
    {
      map[yoff][xoff] = CHAR_LADDER;
      ++yoff;
    }
  return (0);
}

int	gen_floor(char **map, int x, int y)
{
  int	i;
  int	j;
  int	d;
  int	l;

  i = random() % (y - 2) + 1;
  j = random() % (x - 2) + 1;
  map[i][j] = CHAR_WALL;
  d = (random() % 2) ? 1 : -1;
  if (j - 1)
    {
      gen_ladder(map, x, y, j, i);
      l = random() % (j - 1);
      while (l)
	{
	  j += d;
	  if (i >= 1 && i < y - 1 && j > 0 && j < x - 1 && map[i][j] == CHAR_LEVEL)
	    map[i][j] = CHAR_WALL;
	  else
	    break;
	  --l;
	}
    }
  return (0);
}

char	**gen_kong(int x, int y, int d)
{
  char	**map;
  int	i;
  int	j;

  map = malloc((y + 1) * sizeof(*map));
  i = 0;
  while (i < y)
    {
      map[i] = malloc((x + 1) * sizeof(**map));
      j = 0;
      while (j < x)
	{
	  map[i][j] = (i == 0 || j == 0 || i == y - 1 || j == x - 1) ? CHAR_WALL : CHAR_LEVEL;
	  ++j;
	}
      map[i][j] = '\0';
      ++i;
    }
  map[i] = '\0';
  i = -1;
  while (++i < d)
    gen_floor(map, x, y);
  return (map);
}

char	**show_kong(char **map)
{
  int	i;

  if (map == 0)
    return (map);
  i = -1;
  while (map[++i])
    puts(map[i]);
  return (map);
}

int	free_kong(char **map)
{
  int	i;

  if (!map)
    return (0);
  i = -1;
  while (map[++i])
    free(map[i]);
  free(map);
  return (0);
}

int	main(int ac, char **av)
{
  if (ac != 4)
    return (puts("Usage: ./gen_kong size_x size_y difficulty"));
  srandom(getpid() * time(0));
  return (free_kong(show_kong(gen_kong(atoi(av[1]), atoi(av[2]), atoi(av[3])))));
}
